package com.fr;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

/**
*作者：furong
*日期：2016年12月22日
*时间：上午11:54:35
*/
/**
 * Your Trie object will be instantiated and called as such:
 * Trie trie = new Trie();
 * trie.insert("lintcode");
 * trie.search("lint"); will return false
 * trie.startsWith("lint"); will return true
 */
class TrieNode {
    Map<Character, TrieNode> childMap = new HashMap<>();
    Character c;
    boolean isEnd = false;

    public TrieNode() {

    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        if (word != null && word.length() > 0) {
            TrieNode current = root;
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                TrieNode now = current.childMap.get(c);
                if (now == null) {
                    now = new TrieNode();
                    now.c = c;
                    current.childMap.put(c, now);
                    current = now;
                } else {
                    current = now;
                }
            }
            current.isEnd = true;
        }
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        if (word == null || word.length() <= 0) {
            return false;
        }
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            current = current.childMap.get(c);
            if (current == null) {
                return false;
            }
        }
        return current.isEnd;

    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        if (prefix == null || prefix.length() <= 0) {
            return false;
        }
        TrieNode current = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            current = current.childMap.get(c);
            if (current == null) {
                return false;
            }
        }
        return true;
    }

    @Test
    public void testA() {
        Trie trie = new Trie();
        trie.insert("lintcode");
        System.out.println(trie.search("code")); // return false
        System.out.println(trie.startsWith("lint")); // return true
        System.out.println(trie.startsWith("linterror")); // return false
        trie.insert("linterror");
        System.out.println(trie.search("lintcode")); // return true
        System.out.println(trie.startsWith("linterror")); // return true
    }
}
